<?php
/**
 * Created by PhpStorm.
 * User: ZhangWei
 * Date: 2018/4/19
 * Time: 13:56
 */

namespace App\Http\Controllers\Api\Open;


use App\Http\Resources\DocPageCollection;
use App\Models\Doc;
use App\Models\DocPage;
use Illuminate\Http\Request;
use Illuminate\Validation\Rule;

class CollectController extends BaseController
{
    /**
     * @param Request $request
     * @return mixed
     * @throws \App\Exceptions\ApiException
     */
    public function collect_menu(Request $request)
    {
        $user = $this->getUser();
        $id = $this->getId();
        $validator = \Validator::make($request->all(), [
            'source' => ['required', Rule::in(['kancloud', 'gitbook'])],
            'menus' => 'required|string',
        ], [
            'source.required' => '数据来源不可采集',
            'menus.required' => '目录数据不可为空',
        ]);
        if ($validator->fails()) {
            return $this->failed($validator->errors()->first());
        }
        $source = $request->input("source");
        $menus = json_decode($request->input("menus"), true);
        $doc = Doc::withAnyStatus()->where('user_id', $user->id)->findOrFail($id);
        if ($doc->pages()->count() == 0) {
            Doc::allCollectMenu($menus, 0, $source, $doc);
        }
        $pages = $doc->pages()
            ->where([['source', '=', $source], ['content', '=', '']])
            ->orWhere(function ($query) use ($source) {
                $query->where('source', $source)
                    ->whereNull('content');
            })->get(['id', 'source', 'source_key']);

        $data = DocPageCollection::make($pages)->type('collect');
        return $this->success($data);
    }

    public function collect_content(Request $request)
    {
        $user = $this->getUser();
        $id = $this->getId();
        $validator = \Validator::make($request->all(), [
            'pages' => 'required|string',
            'model' => ['required', Rule::in(['md'])],
        ], [
            'content.required' => '内容不能为空'
        ]);
        if ($validator->fails()) {
            return $this->failed($validator->errors()->first());
        }
        $doc = Doc::withAnyStatus()->where('user_id', $user->id)->findOrFail($id);
        $pages = json_decode($request->input("pages"), true);
        foreach ($pages as $v) {
            $page_id = hashid_decode($v['id']);
            $docPage = DocPage::query()->where('doc_id', $doc->id)->where('user_id', $user->id)->findOrFail($page_id);
            $docPage->model = $request->input("model");
            $docPage->content = $v['content'];
            $docPage->save();
        }

        return $this->message("采集成功");

    }

}